from photologue.models import Photo, Place
from django.contrib.gis.geos import Point
import logging

def DmsToDecimal(degree_num, degree_den, minute_num, minute_den,
                 second_num, second_den):
  """Converts the Degree/Minute/Second formatted GPS data to decimal degrees.

  Args:
    degree_num: The numerator of the degree object.
    degree_den: The denominator of the degree object.
    minute_num: The numerator of the minute object.
    minute_den: The denominator of the minute object.
    second_num: The numerator of the second object.
    second_den: The denominator of the second object.

  Returns:
    A deciminal degree.
  """

  degree = float(degree_num)/float(degree_den)
  minute = float(minute_num)/float(minute_den)/60
  second = float(second_num)/float(second_den)/3600
  return degree + minute + second

def lon_lat_from_exif(photo):
    lat_dms = photo.EXIF['GPS GPSLatitude'].values
    long_dms = photo.EXIF['GPS GPSLongitude'].values
    latitude = DmsToDecimal(lat_dms[0].num, lat_dms[0].den,
                          lat_dms[1].num, lat_dms[1].den,
                          lat_dms[2].num, lat_dms[2].den)
    longitude = DmsToDecimal(long_dms[0].num, long_dms[0].den,
                          long_dms[1].num, long_dms[1].den,
                          long_dms[2].num, long_dms[2].den)
    return longitude, latitude

def exif_gps_to_db(photos):
    """
    Takes a queryset of photos, reads the gps fields from the EXIF data, and creates a place
    for each one that does not already exist, named after the photo.
    """

    locations_dict=[]
    for photo in photos:
        try:
            latlon=lon_lat_from_exif(photo)
            place, created=Place.objects.get_or_create(coordinates=Point(latlon, srid=4326),defaults={'title':unicode(photo),'slug':photo.slug})
            photo.place=place
            photo.save()
            logging.debug('Saved place for photo %s' % photo)
        except:
            logging.debug("Couldn't save a place for photo %s" % photo)

